package win.bigwhale.sudoku.view;

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.util.Duration;
import win.bigwhale.sudoku.SudokuUtil;
import win.bigwhale.sudoku.controller.GameControlInterface;
import win.bigwhale.sudoku.controller.GameController;
import win.bigwhale.sudoku.game.Sudoku;

public class TimePane extends HBox implements GameControlInterface {
	private static TimePane timePane = new TimePane();
	private final Label timeStringLabel = new Label("Time");
	private Label timeLabel = new Label("00:00:00");
	private int usedTime = 0;
	private Timeline mTimeline = null;

	private TimePane() {
		GameController.getGameController().addPane(this);
		setPrefSize(130.0, 50.0);
		setLayoutX(10.0);
		setLayoutY(10.0);
		setBackground(SudokuUtil.PANE_BACKGROUND);
		setAlignment(Pos.CENTER);

		getChildren().add(timeStringLabel);
		getChildren().add(timeLabel);
		HBox.setMargin(timeStringLabel, new Insets(0.0, 4.0, 0.0, 0.0));
		
		mTimeline = new Timeline(new KeyFrame(Duration.millis(1000), new CountTimeEventHandler()));
		mTimeline.setCycleCount(Timeline.INDEFINITE);
	}

	public static TimePane getTimePane() {
		return timePane;
	}

	protected String getUsedTime() {
		int second = usedTime % 60;
		int minute = usedTime / 60 % 60;
		int hour = usedTime / 3600;
		
		String secondStr = new Integer(second).toString();
		if (secondStr.length() == 1) {
			secondStr = "0" + secondStr;
		}
		
		String minuteStr = new Integer(minute).toString();
		if (minuteStr.length() == 1) {
			minuteStr = "0" + minuteStr;
		}
		
		String hourStr = new Integer(hour).toString();
		if (hourStr.length() == 1) {
			hourStr = "0" + hourStr;
		}
		
		return hourStr+":"+minuteStr+":"+secondStr;
	}

	private final class CountTimeEventHandler implements EventHandler<ActionEvent> {
		@Override
		public void handle(ActionEvent event) {
			++usedTime;
			timeLabel.setText(getUsedTime());
		}
	}

	@Override
	public void startGame(Sudoku sudoku) {
		mTimeline.play();
	}

	@Override
	public void pauseGame() {
		mTimeline.pause();
	}

	@Override
	public void restartGame() {
		timeLabel.setText("00:00:00");
		mTimeline.play();
		usedTime = 0;
	}

	@Override
	public void endGame() {
		usedTime = 0;
		timeLabel.setText("00:00:00");
		mTimeline.stop();
	}

	@Override
	public void completeGame() {
		mTimeline.stop();
	}

	@Override
	public void resumeGame() {
		mTimeline.play();
	}
}
